import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:fate_blind_box/chat_view/video_push_widget.dart';
import 'package:fate_blind_box/config/app_utils.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/assets.dart';
import 'package:fate_blind_box/utils/bottom_sheet.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/picker.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_picker/picker.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:universal_html/html.dart' as html;

import '../../utils/loading.dart';
import '../../widget/photo_view.dart';
import 'MeIntroduce.dart';
import 'modifyNick.dart';

class ProfileEditUi extends StatelessWidget {
  const ProfileEditUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _ProfileEditWidget();
  }
}

class _ProfileEditWidget extends StatefulWidget {
  const _ProfileEditWidget({Key? key}) : super(key: key);

  @override
  State<_ProfileEditWidget> createState() => _ProfileEditWidgetState();
}

class _ProfileEditWidgetState extends State<_ProfileEditWidget> {
  late double _screenWidth;
  final _user = <String, dynamic>{};
  final _mcs = <String, dynamic>{};
  final _desController = TextEditingController();
  late BuildContext _builderContext;
  final List<dynamic> _avatarList = [];
  String? _albumId = "";
  final _nationList = [];
  final _pcaList = [];
  final _pcaOriginalList = [];
  String _sex = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initNations();
    _getMemberInfo();
    _getAlbum();
    _getPcaList();
  }

  @override
  Widget build(BuildContext context) {
    _screenWidth = MediaQuery.of(context).size.width;
    return AppWidget.navTitleBar(
      bgColor: Colors.white,
      title: "我的资料",
      childWidget: Builder(
        builder: (ctx) {
          _builderContext = ctx;
          return Stack(
            children: [
              Container(
                margin: const EdgeInsets.only(left: 14, right: 14),
                child: Column(
                  children: [
                    Expanded(child: _buildContent()),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  /// 标题栏
  Widget _buildTitleBar() {
    return Container(
        height: 56,
        width: _screenWidth,
        color: Colors.transparent,
        alignment: Alignment.centerLeft,
        child: GestureDetector(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: const SizedBox(
            width: 56,
            height: 56,
            child: Icon(
              Icons.arrow_back_ios_new,
              color: Colors.white,
              size: 16,
            ),
          ),
        ));
  }

  /// 内容
  Widget _buildContent() {
    final list = <Widget>[];

    final bgList = <Widget>[];
    bgList.addAll(_buildBasicInfo());

    list.add(Container(
      decoration: const ShapeDecoration(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(15)),
          ),
          color: Colors.white),
      child: Column(
        children: bgList,
      ),
    ));

    return SingleChildScrollView(
      physics: const BouncingScrollPhysics(),
      child: Column(children: list),
    );
  }

  /// 头像和信息完成进度
  Widget _buildAvatarProgress() {
    return Stack(
      children: [],
    );
  }

  /// 信息标题
  Widget _buildInfoTitle(String percent, String title, String subTitle) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              title,
              style: TextStyle(
                  color: ThemeColor.textColor,
                  fontSize: 14,
                  fontWeight: FontWeight.bold),
            ),
            subTitle == ""
                ? Container()
                : Container(
                    height: 20,
                    width: 100,
                    decoration: BoxDecoration(
                      color: const Color(0xffB39EED),
                      borderRadius: BorderRadius.circular(5.0),
                    ),
                    alignment: Alignment.center,
                    margin: const EdgeInsets.only(top: 10),
                    child: Text(
                      subTitle,
                      style: const TextStyle(
                          color: Color(0xff7F69D9), fontSize: 12),
                    ),
                  ),
            Text(
              percent,
              style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 12),
            ),
          ],
        ),
      ],
    );
  }

  /// 个人照片
  List<Widget> _buildPersonalGallery() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                "个人照片",
                style: TextStyle(
                    color: ThemeColor.textColor,
                    fontSize: 14,
                    fontWeight: FontWeight.bold),
              ),
              Text(
                "（${_avatarList.length}/9）",
                style: const TextStyle(color: Color(0xff7F69D9), fontSize: 12),
              ),
            ],
          ),
          Text(
            '20%',
            style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 12),
          ),
        ],
      ),
      Container(
        margin: const EdgeInsets.only(bottom: 22, top: 14),
        height: 77,
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: _avatarList.length < 9 ? _avatarList.length + 1 : 9,
          itemBuilder: (ctx, index) {
            dynamic img;
            if (index < _avatarList.length) {
              img = _avatarList[index];
            }
            return Stack(
              children: [
                Container(
                  margin: const EdgeInsets.symmetric(horizontal: 10),
                  width: 77,
                  height: 77,
                  child: _avatarList.length < 9 && index == _avatarList.length
                      ? GestureDetector(
                          onTap: () {
                            _checkPermissions('照片');
                          },
                          child: Container(
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                border: Border.all(
                                    color: ThemeColor.dividerColor, width: 2),
                                borderRadius: BorderRadius.circular(4)),
                            child: Icon(
                              Icons.add_a_photo,
                              color: ThemeColor.textColorSecond,
                              size: 24,
                            ),
                          ),
                        )
                      : GestureDetector(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (_) => PhotoPreview(
                                          galleryItems: _avatarList,
                                          defaultImage: index,
                                        )));
                          },
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(4),
                            child: img is html.File
                                ? Image.file(
                                    img as File,
                                    width: 77,
                                    height: 77,
                                    fit: BoxFit.cover,
                                  )
                                : Image.network(
                                    _avatarList[index],
                                    width: 77,
                                    height: 77,
                                    fit: BoxFit.cover,
                                  ),
                          ),
                        ),
                ),
                GestureDetector(
                  child: index != _avatarList.length
                      ? Container(
                          margin: const EdgeInsets.only(left: 72),
                          child: Image.asset(
                            "images/ic_editorDelete.png",
                            width: 15,
                            height: 15,
                          ),
                        )
                      : Container(),
                  onTap: () {
                    _deletePhoto(context, img, '放弃上传这张照片吗？');
                  },
                )
              ],
            );
          },
        ),
      ),
    ];
  }

  Future<void> _deletePhoto(context, String img, String title) async {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: Text(title),
            actions: <Widget>[
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: const Text(
                  '取消',
                  style: TextStyle(fontSize: 16, color: Colors.black),
                ),
              ),
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.pop(context);
                  _getDeletePhoto(img);
                },
                child: Text(
                  '确定',
                  style: TextStyle(fontSize: 16, color: ThemeColor.appColor),
                ),
              ),
            ],
          );
        });
  }

  /// 个人简介
  List<Widget> _buildPersonalDes() {
    return [
      Divider(
        indent: 0,
        endIndent: 0,
        height: 6,
        thickness: 6,
        color: Colors.grey[200],
      ),
      Container(
        margin: const EdgeInsets.only(top: 13, bottom: 13),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "个人简介",
                  style: TextStyle(
                      color: ThemeColor.textColor,
                      fontSize: 14,
                      fontWeight: FontWeight.bold),
                ),
                Container(
                  height: 22,
                  width: 100,
                  // width: 100,
                  decoration: BoxDecoration(
                    color: const Color.fromRGBO(127, 105, 217, 0.14),
                    borderRadius: BorderRadius.circular(11),
                  ),
                  alignment: Alignment.center,
                  margin: const EdgeInsets.only(
                      left: 5, right: 8, top: 0, bottom: 0),
                  child: Text(
                    _user['signature'] ?? " 介绍一下自己 ",
                    overflow: TextOverflow.ellipsis,
                    style:
                        const TextStyle(color: Color(0xff7F69D9), fontSize: 12),
                  ),
                ),
              ],
            ),
            InkWell(
              //个人简介
              onTap: () {
                Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                MeIntroduce(_user['signature'].toString())))
                    .then((result) => result ? _getMemberInfo() : null);
              },
              child: Row(
                children: [
                  Container(
                    margin: const EdgeInsets.only(right: 5),
                    child: Text(
                      '10%',
                      style: TextStyle(
                          color: ThemeColor.textColorSecond, fontSize: 12),
                    ),
                  ),
                  Icon(
                    Icons.arrow_forward_ios,
                    size: 14,
                    color: ThemeColor.textColorSecond,
                  )
                ],
              ),
            ),
          ],
        ),
      ),
      Divider(
        indent: 0,
        endIndent: 0,
        height: 6,
        thickness: 6,
        color: Colors.grey[200],
      ),
    ];
  }

  /// 信息item
  Widget _buildInfoItem(String key, dynamic value, String id,
      {bool isHiddenArrow = false}) {
    return GestureDetector(
      onTap: () {
        _onClick(id);
      },
      child: Container(
        height: 52,
        // margin: const EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(width: 1, color: ThemeColor.dividerColor),
          ),
        ),
        child: Row(
          children: [
            Text(
              key,
              style: TextStyle(color: ThemeColor.textColor, fontSize: 16),
            ),
            Expanded(
                child: Text(
              "$value",
              textAlign: TextAlign.right,
              style: TextStyle(color: ThemeColor.colorD88E4B, fontSize: 12),
            )),
            const SizedBox(
              width: 8,
            ),
            // TextField(key, style: TextStyle(color: ThemeColor.mainColor, fontSize: 16),),
            Offstage(
                offstage: isHiddenArrow,
                child: Icon(
                  Icons.arrow_forward_ios,
                  size: 14,
                  color: ThemeColor.textColorSecond,
                ))
          ],
        ),
      ),
    );
  }

  /// 基本资料
  List<Widget> _buildBasicInfo() {
    if (_user.isEmpty) {
      return List.empty();
    }
    return [
      Container(
        margin: const EdgeInsets.only(top: 14, bottom: 14),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              "基本资料",
              style: TextStyle(
                  color: ThemeColor.textColor,
                  fontSize: 14,
                  fontWeight: FontWeight.bold),
            ),
          ],
        ),
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                margin: const EdgeInsets.only(right: 5),
                child: Text(
                  "头像",
                  style: TextStyle(
                      color: ThemeColor.textColor,
                      fontSize: 16,
                      fontWeight: FontWeight.normal),
                ),
              ),
            ],
          ),
          InkWell(
            onTap: () => _checkPermissions('头像'),
            child: Row(
              children: [
                Container(
                  margin: const EdgeInsets.only(right: 5),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(5),
                    child: CachedNetworkImage(
                      imageUrl: Provider.fixAvatar(_user['profilePhoto'] ?? ""),
                      width: 30,
                      height: 30,
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
                Icon(
                  Icons.arrow_forward_ios,
                  size: 14,
                  color: ThemeColor.textColorSecond,
                )
              ],
            ),
          ),
        ],
      ),
      _buildInfoItem("昵称", _user['nickName'] ?? "", "NAME"),
      _buildInfoItem('性别', _sex, 'GENDER', isHiddenArrow: true),
    ];
  }

  String _getIncome(type) {
    List income = [
      '5万~10万',
      '10万~20万',
      '20万~50万',
      '50万~100万',
      '100万~300万',
      '300万以上'
    ];
    if (type == null || type < 0 || type >= income.length) {
      return "--";
    }
    return income[type];
  }

  String _getEdu(type) {
    List edu = ['小学', '初中', '高中', '大专', '本科', '硕士', '博士', '教授'];
    if (type == null || type < 0 || type >= edu.length) {
      return '--';
    }
    return edu[type];
  }

  String _getMarital(status) {
    switch (status) {
      case 0:
        return "未婚";
      case 1:
        return "已婚";
      case 2:
        return "再婚";
      case 3:
        return "离异";
      case 4:
        return "丧偶";
      default:
        return "--";
    }
  }

  /// 家庭情况
  List<Widget> _buildFamily() {
    return [
      _buildInfoTitle("+10%", "家庭情况", ""),
      _buildInfoItem("父亲职业", "无业", "FATHER_PROFESSION"),
      _buildInfoItem("母亲职业", "无业", "MOTHER_PROFESSION"),
      _buildInfoItem("是否与父母同住", "是", "LIVE_PARENT_TOGETHER"),
    ];
  }

  /// 婚姻规划
  List<Widget> _buildMarriagePlan() {
    return [
      _buildInfoTitle("+10%", "婚姻规划", ""),
      _buildInfoItem("是否接受异地", "否", "OFFSIDE"),
      _buildInfoItem("是否要小孩", "是", "HAVE_BABY"),
      _buildInfoItem("是否愿意与父母同住", "是", "LIVE_WITH_PARENT"),
    ];
  }

  /// 择偶要求
  List<Widget> _buildSpouseRequirement() {
    return [
      _buildInfoTitle("+10%", "择偶要求", ""),
      _buildInfoItem("年龄", "${_mcs['ageStart'] ?? 18}~${_mcs['ageEnd'] ?? 50}",
          "SPOUSE_AGE"),
      _buildInfoItem(
          "身高",
          "${_mcs['heightStart'] ?? 150}~${_mcs['heightEnd'] ?? 200}",
          "SPOUSE_HEIGHT"),
      _buildInfoItem(
          "体重",
          "${_mcs['weightStart'] ?? 40}kg~${_mcs['weightEnd'] ?? 100}kg",
          "SPOUSE_WEIGHT"),
      // _buildInfoItem("所在城市", "北京", "SPOUSE_LIVE"),
      _buildInfoItem("学历", _getEdu(_mcs['edu'] ?? 0), "SPOUSE_EDUCATION"),
      _buildInfoItem(
          "年收入", _getIncome(_mcs['incomeVal'] ?? 0), "SPOUSE_INCOME"),
      _buildInfoItem("购车", _mcs['buyCar'] == 1 ? "是" : "否", "SPOUSE_CAR"),
      _buildInfoItem("购房", _mcs['purchase'] == 1 ? "是" : "否", "SPOUSE_HOUSE"),
    ];
  }

  /// 表单提交按钮
  Widget _buildFormSubmitBtn() {
    return GestureDetector(
        onTap: () {
          _onClick("FORM_SUBMIT");
        },
        child: Container(
            height: 44,
            margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 24),
            decoration: ShapeDecoration(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(22)),
                color: ThemeColor.appColor),
            alignment: Alignment.center,
            child: const Text(
              "保存",
              style: TextStyle(color: Colors.white),
            )));
  }

  /// 点击事件
  void _onClick(String id) async {
    print(id);
    switch (id) {
      case 'GENDER':
        // showPicker(_builderContext, ['男', '女'], (picker, value) {
        //   setState(() {
        //     setState(() { _user['realSex'] = value[0] + 1; });
        //   });
        // });
        break;
      case 'NATIONALITY':
        final nas = <String>[];
        for (var element in _nationList) {
          nas.add(element['name']);
        }
        showPicker(_builderContext, nas, (picker, value) {
          setState(() {
            _user['nation'] = _nationList[value[0]]['id'];
          });
        });

        break;
      case 'HEIGHT':
        final list = <String>[];
        for (int i = 150; i <= 230; i++) {
          list.add("${i}cm");
        }
        final defHeight =
            _user['height'] ?? (_user['realSex'] == 1 ? 170 : 160);
        var position = defHeight - 150;
        showPickerWithDefaultPosition(_builderContext, list, position,
            (picker, value) {
          setState(() {
            _user['height'] =
                picker.getSelectedValues()[0].toString().replaceAll("cm", "");
          });
        });
        break;
      case 'WEIGHT':
        final list = <String>[];
        final defWeight = _user['weight'] ?? 55;
        var position = defWeight - 35;
        for (int i = 35; i <= 100; i++) {
          list.add("${i}kg");
        }
        showPickerWithDefaultPosition(_builderContext, list, position,
            (picker, value) {
          setState(() {
            _user['weight'] =
                picker.getSelectedValues()[0].toString().replaceAll("kg", "");
          });
        });
        break;
      case 'BIRTH_DAY':
        final cur = DateTime.now();
        // DatePicker.showDatePicker(context,
        //     showTitleActions: true,
        //     minTime: DateTime(1970, 01, 01,0,0),
        //     maxTime: DateTime(cur.year, cur.month, cur.day),
        //     onConfirm: (date) {
        //       setState(() {
        //         _user['bornDate'] = "${date.year}-${date.month}-${date.day}";
        //       });
        //     }, currentTime: DateTime.tryParse("1980-01-01"), locale: LocaleType.zh);
        break;
      case 'ZODIAC':
        final zodiac = [
          "鼠",
          "牛",
          "虎",
          "兔",
          "龙",
          "蛇",
          "马",
          "羊",
          "猴",
          "鸡",
          "狗",
          "猪",
          "双鱼座"
        ];
        showPicker(_builderContext, zodiac, (picker, value) {
          setState(() {
            _user['animalSign'] = zodiac[value[0]];
          });
        });
        break;
      case 'CONSTELLATION':
        final constellation = [
          "白羊座",
          "金牛座",
          "双子座",
          "巨蟹座",
          "狮子座",
          "白羊座",
          "处女座",
          "天秤座",
          "天蝎座",
          "射手座",
          "摩羯座",
          "水瓶座",
          "双鱼座"
        ];
        showPicker(_builderContext, constellation, (picker, value) {
          setState(() {
            _user['constellation'] = constellation[value[0]];
          });
        });
        break;
      case 'BLOOD':
        final blood = ['A', 'B', 'AB', 'O', 'Rh'];
        showPicker(_builderContext, blood, (picker, value) {
          setState(() {
            _user['blood'] = blood[value[0]];
          });
        });
        break;
      case 'LIVE_ADDRESS':
        showPicker(_builderContext, _pcaList, (picker, selected) {
          final p = _pcaOriginalList[selected[0]]['name'];
          final c =
              _pcaOriginalList[selected[0]]['children'][selected[1]]['name'];
          final a = _pcaOriginalList[selected[0]]['children'][selected[1]]
              ['children'][selected[2]]['name'];
          setState(() {
            _user['homeAddr'] = '$p $c $a ';
          });
        });
        break;
      case 'BIRTH_ADDRESS':
        showPicker(_builderContext, _pcaList, (picker, selected) {
          final p = _pcaOriginalList[selected[0]]['name'];
          final c =
              _pcaOriginalList[selected[0]]['children'][selected[1]]['name'];
          final a = _pcaOriginalList[selected[0]]['children'][selected[1]]
              ['children'][selected[2]]['name'];
          setState(() {
            _user['domicilePlace'] = '$p $c $a ';
          });
        });
        break;
      case 'MARRIAGE':
        showPicker(_builderContext, ['未婚', '已婚', '再婚', '离异', '丧偶'],
            (picker, value) {
          setState(() {
            _user['maritalStatus'] = value[0];
          });
        });
        break;
      case 'BABY':
        showPicker(_builderContext, ['无', '1', '2', '3', '4', '5', '6'],
            (picker, value) {
          setState(() {
            _user['childNum'] = value[0];
          });
        });
        break;
      case 'EDUCATION':
        showPicker(
            _builderContext, ['小学', '初中', '高中', '大专', '本科', '硕士', '博士', '教授'],
            (picker, value) {
          setState(() {
            _user['edu'] = value[0];
          });
        });
        break;
      case 'NAME':
        // final value = await BottomSheetDialog.edit(context);
        // print('=====================');
        // print(value);
        // if (value != null) {
        //   setState(() {
        //     _user['nickName'] = value;
        //   });
        // }

        Navigator.of(context)
            .push(MaterialPageRoute(
                builder: (ctx) => ModifyNickUI(_user['nickName'].toString())))
            .then((value) => value ? _getMemberInfo() : null);
        break;
      case 'PROFESSION':
        final value = await BottomSheetDialog.edit(context);

        if (value != null) {
          setState(() {
            _user['occipation'] = value;
          });
        }
        break;
      case 'INCOME':
        showPicker(_builderContext, [
          '5万~10万',
          '10万~20万',
          '20万~50万',
          '50万~100万',
          '100万~300万',
          '300万以上'
        ], (picker, value) {
          setState(() {
            _user['incomeVal'] = value[0];
          });
        });
        break;
      case 'HOUSE':
        showPicker(_builderContext, ['无房', '有房'], (picker, value) {
          setState(() {
            _user['purchase'] = value[0];
          });
        });
        break;
      case 'CAR':
        showPicker(_builderContext, ['无车', '有车'], (picker, value) {
          setState(() {
            _user['buyCar'] = value[0];
          });
        });
        break;
      case 'SMOKING':
        showPicker(_builderContext, ['否', '抽烟', '喝酒', '抽烟也喝酒'],
            (picker, value) {
          setState(() {
            _user['aat'] = value[0];
          });
        });
        break;
      case 'DRINK_WINE':
        showPicker(_builderContext, ['否', '是'], (picker, value) {
          setState(() {
            _user['wine'] = value[0];
          });
        });
        break;
      case 'FATHER_PROFESSION':
        break;
      case 'MOTHER_PROFESSION':
        break;
      case 'LIVE_PARENT_TOGETHER':
        break;
      case 'OFFSIDE':
        break;
      case 'HAVE_BABY':
        break;
      case 'LIVE_WITH_PARENT':
        break;
      case 'SPOUSE_AGE':
        showNumberPicker(
            _builderContext,
            NumberPickerAdapter(data: [
              const NumberPickerColumn(begin: 18, end: 50),
              const NumberPickerColumn(begin: 18, end: 50),
            ]), (picker, value) {
          final vMin = 18 + min(value[0], value[1]);
          final vMax = 18 + max(value[0], value[1]);
          setState(() {
            _mcs['ageStart'] = vMin;
            _mcs['ageEnd'] = vMax;
          });
        });
        break;
      case 'SPOUSE_HEIGHT':
        showNumberPicker(
            _builderContext,
            NumberPickerAdapter(data: [
              const NumberPickerColumn(begin: 150, end: 200),
              const NumberPickerColumn(begin: 150, end: 200),
            ]), (picker, value) {
          final vMin = 150 + min(value[0], value[1]);
          final vMax = 150 + max(value[0], value[1]);
          setState(() {
            _mcs['heightStart'] = vMin;
            _mcs['heightEnd'] = vMax;
          });
        });
        break;
      case 'SPOUSE_WEIGHT':
        showNumberPicker(
            _builderContext,
            NumberPickerAdapter(data: [
              const NumberPickerColumn(begin: 40, end: 100),
              const NumberPickerColumn(begin: 40, end: 100),
            ]), (picker, value) {
          final vMin = 40 + min(value[0], value[1]);
          final vMax = 40 + max(value[0], value[1]);
          setState(() {
            _mcs['weightStart'] = vMin;
            _mcs['weightEnd'] = vMax;
          });
        });
        break;
      case 'SPOUSE_LIVE':
        // final value = await BottomSheetDialog.edit(context);
        // if (value != null) {
        //   setState(() {
        //     _user['homeAddr'] = value;
        //   });
        // }
        break;
      case 'SPOUSE_EDUCATION':
        showPicker(
            _builderContext, ['小学', '初中', '高中', '大专', '本科', '硕士', '博士', '教授'],
            (picker, value) {
          setState(() {
            _mcs['edu'] = value[0];
          });
        });
        break;
      case 'SPOUSE_INCOME':
        showPicker(_builderContext, [
          '5万~10万',
          '10万~20万',
          '20万~50万',
          '50万~100万',
          '100万~300万',
          '300万以上'
        ], (picker, value) {
          setState(() {
            _mcs['incomeVal'] = value[0];
          });
        });
        break;
      case 'SPOUSE_CAR':
        showPicker(_builderContext, ['否', '是'], (picker, value) {
          setState(() {
            _mcs['buyCar'] = value[0];
          });
        });
        break;
      case 'SPOUSE_HOUSE':
        showPicker(_builderContext, ['否', '是'], (picker, value) {
          setState(() {
            _mcs['purchase'] = value[0];
          });
        });
        break;
      case 'FORM_SUBMIT':
        _submit();
        break;
      default:
        break;
    }
  }

  void _getMemberInfo() async {
    final res = await Api.getInstance().getMemberInfo(Provider.memberId);
    print('vvv $res');
    if (res['code'] == 0) {
      setState(() {
        _user.clear();
        _user.addAll(res['data']);
        //0空 1男 2女
        if (_user['realSex'] == 0) {
          _sex = '';
        } else if (_user['realSex'] == 1) {
          _sex = '男';
        } else if (_user['realSex'] == 2) {
          _sex = '女';
        }
        if (_user['mcs'] != null) {
          _mcs.clear();
          _mcs.addAll(_user['mcs']);
        }
      });

      // _desController.text = _user['signature'].isNull?"介绍一下自己":_user['signature'];
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  //删除照片
  void _getDeletePhoto(String photoImg) async {
    print(photoImg);
    final res = await Api.getInstance().getDeletePhoto(photoImg);
    if (res['code'] == 0) {
      setState(() {
        _avatarList.clear();
        _getAlbum();
        // _checkPhoto();
        // _avatarList();
        // _checkPhoto2();
      });
      ThemeSnackBar.show(context, res['msg']);
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  void _submit() {
    loading(() async {
      _user['signature'] = _desController.text;

      final info = await Api.getInstance().modifyProfile(_user);

      print('sss $_mcs');
      final mcsRes = await Api.getInstance().modifyMcs(_mcs);

      Navigator.pop(context);
      ThemeSnackBar.show(context, '保存成功');
    });
  }

  /// 头像
  _checkAvatar() {
    if (!kIsWeb) {
      loading(() async {
        final picker = ImagePicker();
        final pickerFile = await picker.pickImage(source: ImageSource.gallery);
        if (pickerFile != null) {
          CroppedFile? croppedImage = await ImageCropper().cropImage(
              maxHeight: 500,
              maxWidth: 500,
              sourcePath: pickerFile.path,
              //图片资源
              aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
              //裁剪框比例
              uiSettings: [
                AndroidUiSettings(
                    toolbarTitle: '裁剪', lockAspectRatio: true //锁定图片纵横比
                    ),
                IOSUiSettings(
                    title: '裁剪',
                    resetButtonHidden: true,
                    //不显示重置按钮
                    aspectRatioLockEnabled: true,
                    //锁定图片纵横比
                    aspectRatioPickerButtonHidden: true,
                    //隐藏切换纵横比按钮
                    doneButtonTitle: "完成",
                    //confirm按钮文字
                    cancelButtonTitle: "取消" //cancel按钮文字
                    )
              ]); //根据XFile对象的路径获得图片进行裁剪
          //裁剪完成

          if (croppedImage != null) {
            //裁剪后图片的路径
            String filepath = croppedImage.path;
            final res = await Api.getInstance()
                .uploadAvatar(Provider.memberId, filepath); //pickerFile.path
            if (res['code'] == 0) {
              setState(() {
                ThemeSnackBar.show(context, res['msg']);
                _user['profilePhoto'] = res['data']['url'];
                Provider.userInfo.value?.profilePhoto = res['data']['url'];
                Provider.userInfo.refresh();
                EMClient.getInstance.userInfoManager.updateUserInfo(
                  avatarUrl: res['data']['url'],
                );
              });
            } else {
              ThemeSnackBar.show(context, res['msg']);
            }
            print("filepath-----$filepath");
          }
        }
      });
    } else {
      final uploadInputElement = html.FileUploadInputElement();
      uploadInputElement.multiple = false;
      uploadInputElement.draggable = true;
      uploadInputElement.click();
      uploadInputElement.onChange.listen((event) {
        final file = uploadInputElement.files?.first;
        if (file != null) {
          loading(() async {
            final formData = html.FormData();
            formData.appendBlob("avatarfile", file.slice(), file.name);
            formData.append("memberId", Provider.memberId);
            Api.getInstance().uploadAvatarFromHtml(formData, (e) {
              if (e['code'] == 0) {
                setState(() {
                  _user['profilePhoto'] = e['data']['url'];
                  Provider.userInfo.value?.profilePhoto = e['data']['url'];
                  Provider.userInfo.refresh();
                  EMClient.getInstance.userInfoManager.updateUserInfo(
                    avatarUrl: e['data']['url'],
                  );
                });
              } else {
                ThemeSnackBar.show(context, e['msg']);
              }
            });
          });
        }
      });
    }
  }

  /// 获取相册
  _getAlbum() async {
    final res = await Api.getInstance().getAlbum();
    print('oooo $res');
    if (res['code'] == 0) {
      if (res['data'] == null || res['data'].length == 0) {
        final addAlbum =
            await Api.getInstance().addAlbum("${_user['nickName']}的相册", "");
        print('rrrr $addAlbum');
        if (addAlbum['code'] == 0) {
          _albumId = addAlbum['data'];
        } else {
          ThemeSnackBar.show(context, "创建相册失败");
        }
      } else {
        String? photos = res['data'][0]["photoImg"];
        _albumId = res['data'][0]['id'];
        if (_albumId?.isEmpty == true) {
          ThemeSnackBar.show(context, "获取相册失败！");
        } else if (photos != null && photos.isNotEmpty) {
          List<String> pList = photos.split(",");
          setState(() {
            for (var value in pList) {
              if (value.isNotEmpty) {
                _avatarList.insert(_avatarList.length, value);
              }
            }
          });
        }
      }
    }
  }

  // 权限申请
  permissionTips(String type) async {
    if (Platform.isAndroid) {
      var status = await permissionDialog(
        context,
        title: "“都肆商圈”需要使用您的相册权限，是否允许？",
        content: type == '照片' ? '不允许您将无法选择照片' : '不允许您将无法发送更换头像',
      );
      if (status == '不允许') {
        return;
      }
    }
    requestPermission(type);
  }

  ///申请权限
  void requestPermission(String type) async {
    var permission = await AppUtils.getPhotoPermission();
    PermissionStatus status = await permission.request();
    if (status.isGranted) {
      type == '照片' ? _checkPhoto() : _checkAvatar();
    }
  }

  _checkPermissions(String type) async {
    bool isGranted = await AppUtils.permissionPhotos();
    if (isGranted) {
      type == '照片' ? _checkPhoto() : _checkAvatar();
    } else {
      permissionTips(type);
    }
  }

  /// 照片墙-选取照片
  _checkPhoto() {
    if (_albumId?.isEmpty == true) {
      ThemeSnackBar.show(context, "无效的相册");
      return;
    }
    if (kIsWeb) {
      final uploadInputElement = html.FileUploadInputElement();
      uploadInputElement.multiple = false;
      uploadInputElement.draggable = true;
      uploadInputElement.click();
      uploadInputElement.onChange.listen((event) {
        final file = uploadInputElement.files?.first;
        if (file != null) {
          Api.getInstance().addPic2AlbumHtml(_albumId!, [file], (res) {
            final list = res['data'];
            if (list == null || list.isEmpty) {
              ThemeSnackBar.show(context, "上传失败");
            } else {
              setState(() {
                for (var value in list) {
                  if (value.isNotEmpty) {
                    _avatarList.insert(_avatarList.length, value['photoImg']);
                  }
                }
              });
            }
            dismissLoading();
          });
        }
      });
    } else {
      loading(() async {
        final picker = ImagePicker(); //maxHeight: 700,maxWidth: 500
        final XFile? pickerFile = await picker.pickImage(
          source: ImageSource.gallery,
          maxWidth: 1000,
        );
        if (pickerFile != null) {
          final res = await Api.getInstance()
              .addPic2Album(_albumId!, [pickerFile.path]);
          print('zzz $res');
          if (res?['code'] == 0) {
            final list = res['data'];
            if (list == null || list.isEmpty) {
              toast("发生了一个未知错误");
            } else {
              setState(() {
                for (var value in list) {
                  print('bbbb $value ${_avatarList.length}');
                  if (value.isNotEmpty) {
                    _avatarList.insert(_avatarList.length, value['photoImg']);
                  }
                }
              });
            }
            toast(res?['msg']);
          } else {
            toast(res?['msg'] ?? "上传失败...");
          }
        }
      });
    }
  }

  /// 个人照片
  _checkPhoto2() {
    if (_albumId?.isEmpty == true) {
      ThemeSnackBar.show(context, "无效的相册");
      return;
    }
    final uploadInputElement = html.FileUploadInputElement();
    uploadInputElement.multiple = false;
    uploadInputElement.draggable = true;
    uploadInputElement.click();
    uploadInputElement.onChange.listen((event) {
      final file = uploadInputElement.files?.first;
      if (file != null) {
        EasyLoading.show();
        Api.getInstance().personalPhotos(file, (res) {
          final url = res['data'];
          if (url == null) {
            ThemeSnackBar.show(context, "上传失败");
          } else {
            setState(() {
              _avatarList.insert(_avatarList.length, url);
            });
          }
          EasyLoading.dismiss();
        });
      }
    });
  }

  /// 获取民族列表
  _initNations() async {
    final str = await loadAsset("nationality.json");
    List obj = json.decode(str);
    for (var element in obj) {
      _nationList.add(element);
    }
  }

  /// 根据id获取民族名称
  String _getNationById(id) {
    var s = "";
    for (var value in _nationList) {
      if (value['id'] == id) {
        s = value['name'];
        break;
      }
    }
    return s;
  }

  /// 获取省市县列表
  _getPcaList() async {
    final Response<dynamic> res = await Api.getInstance().getPcaList();
    _pcaOriginalList.addAll(res.data);
    for (var i in res.data) {
      final item = <String, dynamic>{};
      final cities = [];
      for (var c in i['children']) {
        final area = [];
        final city = <String, dynamic>{};
        for (var a in c['children']) {
          area.add(a['name']);
        }
        city[c['name']] = area;
        cities.add(city);
      }
      item[i['name']] = cities;
      _pcaList.add(item);
    }
  }

  Future<XFile?> testCompressAndGetFile(File file, String targetPath) async {
    var result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      targetPath,
      quality: 88,
      rotate: 180,
    );
    print(file.lengthSync());

    return result;
  }
}
